<?php


namespace EchoPHP\Memcached;

use EchoPHP\Facades\Log;
use Memcached;

class Connector {

    /**
     * 连接memcache服务器
     * @param array $servers
     * @param null $connectionId
     * @param array $options
     * @return Memcached
     */
    public function connect(array $servers, $connectionId = null, array $options = []) {
        $memcached = $this->getMemcached($connectionId, $options);
        if (!$memcached->getServerList()) {
            foreach ($servers as $server) {
                $memcached->addServer(
                    $server['host'], $server['port'], $server['weight']
                );
            }

            if (false === $memcached->getVersion()) {
                Log::alert('memcache链接出现异常', [
                    'code' => $memcached->getLastErrorCode(),
                    'message' => $memcached->getLastErrorMessage()
                ]);
            }
        }

        return $memcached;
    }

    /**
     * 获取memcached类实例
     * @param $connectionId     共享实例id，如果为空，请求结束后实例会被销毁，通过这个可以创建共享实例以共享同一个连接
     * @param array $options memcached相关参数
     * @return Memcached
     */
    protected function getMemcached($connectionId, array $options) {
        if (empty($connectionId)) {
            $memcached = new Memcached();
        } else {
            $memcached = new Memcached($connectionId);
        }
        if (!empty($options)) {
            $memcached->setOptions($options);
        }
        return $memcached;
    }
}